{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "63edd085-334e-4a3d-bfe5-690b0690d57d",
   "metadata": {},
   "source": [
    "## 2412114323-吴林炜-实验2-2025-09-16"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e348fb5b-4405-4c2d-88e6-b83ea22b7c7c",
   "metadata": {},
   "source": [
    "任务一："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "407a1d17-4a57-4a84-93ab-b6647a0c7fcf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入您的身高(米)： 169\n",
      "请输入您的体重(千克)： 55\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您的BMI值为：0.00\n",
      "根据国际标准，您的身体状况为：偏瘦\n",
      "根据国内标准，您的身体状况为：偏瘦\n"
     ]
    }
   ],
   "source": [
    "class BMICalculator:\n",
    "    \"\"\"BMI计算器类，用于计算BMI值并判断身体状况\"\"\"\n",
    "    \n",
    "    def __init__(self, height, weight):\n",
    "        \"\"\"初始化方法，接收身高(米)和体重(千克)\"\"\"\n",
    "        self.height = height\n",
    "        self.weight = weight\n",
    "        self.bmi = self.calculate_bmi()\n",
    "    \n",
    "    def calculate_bmi(self):\n",
    "        \"\"\"计算BMI值，公式：BMI = 体重 / 身高²\"\"\"\n",
    "        return self.weight / (self.height **2)\n",
    "    \n",
    "    def get_international_category(self):\n",
    "        \"\"\"根据国际标准判断身体状况\"\"\"\n",
    "        if self.bmi < 18.5:\n",
    "            return \"偏瘦\"\n",
    "        elif 18.5 <= self.bmi < 25:\n",
    "            return \"正常\"\n",
    "        elif 25 <= self.bmi < 30:\n",
    "            return \"偏胖\"\n",
    "        else:\n",
    "            return \"肥胖\"\n",
    "    \n",
    "    def get_domestic_category(self):\n",
    "        \"\"\"根据国内标准判断身体状况\"\"\"\n",
    "        if self.bmi < 18.5:\n",
    "            return \"偏瘦\"\n",
    "        elif 18.5 <= self.bmi < 24:\n",
    "            return \"正常\"\n",
    "        elif 24 <= self.bmi < 28:\n",
    "            return \"偏胖\"\n",
    "        else:\n",
    "            return \"肥胖\"\n",
    "    \n",
    "    def display_result(self):\n",
    "        \"\"\"显示计算结果和判断情况\"\"\"\n",
    "        print(f\"您的BMI值为：{self.bmi:.2f}\")\n",
    "        print(f\"根据国际标准，您的身体状况为：{self.get_international_category()}\")\n",
    "        print(f\"根据国内标准，您的身体状况为：{self.get_domestic_category()}\")\n",
    "\n",
    "\n",
    "# 主程序\n",
    "if __name__ == \"__main__\":\n",
    "    # 从键盘输入身高和体重\n",
    "    height = float(input(\"请输入您的身高(米)：\"))\n",
    "    weight = float(input(\"请输入您的体重(千克)：\"))\n",
    "    \n",
    "    # 创建BMI计算器对象并显示结果\n",
    "    bmi_calculator = BMICalculator(height, weight)\n",
    "    bmi_calculator.display_result()\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f35e0163-3992-48eb-aec1-af50bae971a2",
   "metadata": {},
   "source": [
    "任务二："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e92b4432-d8c0-4edb-ae32-cf1667e9f5ec",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入十进制整数： 169\n",
      "请输入转换进制（2或8）： 8\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "十进制数：169=(2 5 1) 8进制 \n"
     ]
    }
   ],
   "source": [
    "class NumberConverter:\n",
    "    \"\"\"数字转换器类，用于将十进制数转换为二进制或八进制\"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        \"\"\"初始化方法，获取用户输入的十进制数和目标进制\"\"\"\n",
    "        self.decimal_num = self.get_decimal_input()\n",
    "        self.target_base = self.get_base_input()\n",
    "        self.result = self.convert()\n",
    "    \n",
    "    def get_decimal_input(self):\n",
    "        \"\"\"获取用户输入的十进制整数\"\"\"\n",
    "        while True:\n",
    "            try:\n",
    "                return int(input(\"请输入十进制整数：\"))\n",
    "            except ValueError:\n",
    "                print(\"输入错误！请输入有效的整数\")\n",
    "    \n",
    "    def get_base_input(self):\n",
    "        \"\"\"获取用户输入的目标进制（2或8）并验证\"\"\"\n",
    "        while True:\n",
    "            try:\n",
    "                base = int(input(\"请输入转换进制（2或8）：\"))\n",
    "                # 确保输入的是2或8\n",
    "                assert base == 2 or base == 8, \"进制必须是2或8\"\n",
    "                return base\n",
    "            except AssertionError as e:\n",
    "                print(f\"输入错误：{e}\")\n",
    "            except ValueError:\n",
    "                print(\"输入错误！请输入整数2或8\")\n",
    "    \n",
    "    def convert(self):\n",
    "        \"\"\"将十进制数转换为指定进制\"\"\"\n",
    "        num = self.decimal_num\n",
    "        \n",
    "        # 处理0的情况\n",
    "        if num == 0:\n",
    "            return \"0\"\n",
    "        \n",
    "        # 处理负数\n",
    "        is_negative = False\n",
    "        if num < 0:\n",
    "            is_negative = True\n",
    "            num = abs(num)\n",
    "        \n",
    "        result = []\n",
    "        div = num\n",
    "        while div != 0:\n",
    "            div, mod = divmod(div, self.target_base)\n",
    "            result.append(str(mod))\n",
    "        \n",
    "        # 反转结果得到正确顺序\n",
    "        result.reverse()\n",
    "        \n",
    "        # 添加负号（如果需要）\n",
    "        result_str = ' '.join(result)\n",
    "        if is_negative:\n",
    "            result_str = '-' + result_str\n",
    "            \n",
    "        return result_str\n",
    "    \n",
    "    def display_result(self):\n",
    "        \"\"\"显示转换结果\"\"\"\n",
    "        print(f'十进制数：{self.decimal_num}=({self.result}) {self.target_base}进制 ')\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # 创建转换器对象并显示结果\n",
    "    converter = NumberConverter()\n",
    "    converter.display_result()\n",
    "    \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b21359a8-b280-4f69-a56d-7f5dfd34504a",
   "metadata": {},
   "source": [
    "任务三："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76838fe7-8dcf-4ffc-a1fa-1c620b48453d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#coding=utf8\n",
    "import datetime\n",
    "import time\n",
    "\n",
    "class CheckinReminder:\n",
    "    def __init__(self, hour=0, minute=0):\n",
    "        self.h, self.m = hour, minute\n",
    "\n",
    "    def run(self):\n",
    "        try:\n",
    "            while True:\n",
    "                now = datetime.datetime.now()\n",
    "                if now.hour == self.h and now.minute == self.m:\n",
    "                    print(f\"{now} 哥们，该用微哨打卡了...\")\n",
    "                    time.sleep(60)  # 避免重复提醒\n",
    "                time.sleep(10)\n",
    "        except KeyboardInterrupt:\n",
    "            print(\"\\n程序已停止\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    CheckinReminder(8, 50).run()\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a2ad3f8-bc80-447a-b16f-73d0a0673b9c",
   "metadata": {},
   "source": [
    "任务四："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "83c3df61-656d-4405-8f5d-75b29e2a4ac8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6 是完全数，真因子为 [1, 2, 3]\n",
      "28 是完全数，真因子为 [1, 2, 4, 7, 14]\n",
      "496 是完全数，真因子为 [1, 2, 4, 8, 16, 31, 62, 124, 248]\n",
      "计算完成，共用时0.0 秒\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "\n",
    "class PerfectNumberCalculator:    \n",
    "    def __init__(self, max_num):\n",
    "        \"\"\"初始化计算器，设置最大数值范围\"\"\"\n",
    "        self.max_num = max_num\n",
    "        self.start_time = 0\n",
    "        self.end_time = 0    \n",
    "    def find_factors(self, num):\n",
    "        \"\"\"查找一个数的所有真因子（不包括自身）\"\"\"\n",
    "        factors = []\n",
    "        for i in range(1, num // 2 + 1):\n",
    "            if num % i == 0:\n",
    "                factors.append(i)\n",
    "        return factors\n",
    "    \n",
    "    def is_perfect(self, num):\n",
    "        \"\"\"判断一个数是否为完全数（真因子之和等于自身）\"\"\"\n",
    "        return num == sum(self.find_factors(num))\n",
    "    \n",
    "    def calculate(self):\n",
    "        \"\"\"计算并输出指定范围内的所有完全数\"\"\"\n",
    "        self.start_time = time.time()\n",
    "        \n",
    "        for num in range(2, self.max_num):\n",
    "            if self.is_perfect(num):\n",
    "                factors = self.find_factors(num)\n",
    "                print(f\"{num} 是完全数，真因子为 {factors}\")\n",
    "        \n",
    "        self.end_time = time.time()\n",
    "        print(f\"计算完成，共用时{self.end_time - self.start_time:.1f} 秒\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # 创建计算器实例，查找2到999之间的完全数\n",
    "    calculator = PerfectNumberCalculator(1000)\n",
    "    calculator.calculate()\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47fa8fbe-4a46-4bab-9260-5c37fd4b26ee",
   "metadata": {},
   "source": [
    "任务五："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "40641c78-4427-4a0c-a7c9-c3a58404214d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入评委人数： 3\n",
      "请输入第1个评委的分数： 9\n",
      "请输入第2个评委的分数： 8\n",
      "请输入第3个评委的分数： 9\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------------------------------------------------------------\n",
      "评委打的原始分\n",
      "[9.0, 8.0, 9.0]\n",
      "---------------------------------------------------------\n",
      "去掉最高分和最低分后的分数\n",
      "[9.0]\n",
      "-----------------------------------------------------------------\n",
      "最后得分\n",
      "9.0\n"
     ]
    }
   ],
   "source": [
    "class ScoreCalculator:\n",
    "    def __init__(self):\n",
    "        self.num_judges = 0\n",
    "        self.scores = []\n",
    "        self.filtered_scores = []\n",
    "        self.mean_score = 0.0\n",
    "\n",
    "    def input_judge_count(self):\n",
    "        \"\"\"获取并验证评委人数\"\"\"\n",
    "        while True:\n",
    "            try:\n",
    "                self.num_judges = int(input(\"请输入评委人数：\"))\n",
    "                if self.num_judges <= 2:\n",
    "                    print(\"评委人数太少，评委人数必须多于 2 人！\")\n",
    "                else:\n",
    "                    break\n",
    "            except ValueError:\n",
    "                print(\"请输入有效的数字！\")\n",
    "\n",
    "    def input_scores(self):\n",
    "        \"\"\"获取并验证每个评委的分数\"\"\"\n",
    "        self.scores = []\n",
    "        for i in range(self.num_judges):\n",
    "            while True:\n",
    "                try:\n",
    "                    score = float(input(f\"请输入第{i + 1}个评委的分数：\"))\n",
    "                    if not (0 <= score <= 10):\n",
    "                        raise ValueError(\"分数必须在0到10之间\")\n",
    "                    self.scores.append(score)\n",
    "                    break\n",
    "                except ValueError as e:\n",
    "                    print(f\"该评委的分数错误！{str(e)} 重新输入：\")\n",
    "\n",
    "    def process_scores(self):\n",
    "        \"\"\"处理分数：去掉最高分和最低分，计算平均分\"\"\"\n",
    "        if not self.scores:\n",
    "            raise ValueError(\"没有分数可处理，请先输入分数\")\n",
    "        \n",
    "        high = max(self.scores)\n",
    "        low = min(self.scores)\n",
    "        \n",
    "        # 复制原始分数列表并移除最高分和最低分\n",
    "        self.filtered_scores = self.scores.copy()\n",
    "        self.filtered_scores.remove(high)\n",
    "        self.filtered_scores.remove(low)\n",
    "        \n",
    "        # 计算平均分并保留三位小数\n",
    "        self.mean_score = round(sum(self.filtered_scores) / len(self.filtered_scores), 3)\n",
    "\n",
    "    def display_results(self):\n",
    "        \"\"\"显示计算结果\"\"\"\n",
    "        print(\"-\" * 60)\n",
    "        print(\"评委打的原始分\")\n",
    "        print(self.scores)\n",
    "        print(\"-\" * 57)\n",
    "        print(\"去掉最高分和最低分后的分数\")\n",
    "        print(self.filtered_scores)\n",
    "        print(\"-\" * 65)\n",
    "        print(\"最后得分\")\n",
    "        print(self.mean_score)\n",
    "\n",
    "    def run(self):\n",
    "        \"\"\"运行整个评分计算流程\"\"\"\n",
    "        self.input_judge_count()\n",
    "        self.input_scores()\n",
    "        self.process_scores()\n",
    "        self.display_results()\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    calculator = ScoreCalculator()\n",
    "    calculator.run()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "281a3280-6512-4ea6-a787-4973ee9078e1",
   "metadata": {},
   "source": [
    "任务六："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f8e989a3-841a-48eb-9632-f124a881c37f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入你包红包的总金额(1-200)： 180\n",
      "请输入抢红包的人数： 10\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "----------------------------------------红包分发结果如下：----------------------------------------\n",
      "[21.44, 27.0, 42.84, 52.34, 30.35, 5.52, 0.11, 0.19, 0.1, 0.11]\n"
     ]
    }
   ],
   "source": [
    "import random as rd\n",
    "\n",
    "def red_lucky_money(amount, num):\n",
    "    moneys = []\n",
    "    total = 0\n",
    "    avg = amount / num\n",
    "    max_one = 3 * avg  \n",
    "    for i in range(num - 1):\n",
    "        remaining = amount - total\n",
    "        min_one = 0.1\n",
    "        max_possible = min(max_one, remaining - (num - i - 1) * 0.1)  \n",
    "        if max_possible < min_one:\n",
    "            max_possible = min_one  \n",
    "        one = round(rd.uniform(min_one, max_possible), 2)\n",
    "        moneys.append(one)\n",
    "        total += one\n",
    "    last = round(amount - total, 2)\n",
    "    moneys.append(last)\n",
    "    return moneys\n",
    "\n",
    "def main():\n",
    "    while True:\n",
    "        try:\n",
    "            amount = int(input(\"请输入你包红包的总金额(1-200)：\"))\n",
    "            assert 1 <= amount <= 200\n",
    "            break\n",
    "        except:\n",
    "            print(\"输入错误！\")\n",
    "    while True:\n",
    "        try:\n",
    "            num = int(input(\"请输入抢红包的人数：\"))\n",
    "            assert 1 <= num <= 100\n",
    "            break\n",
    "        except:\n",
    "            print(\"输入错误！\")\n",
    "    result = red_lucky_money(amount, num)\n",
    "    print(\"-\" * 40 + \"红包分发结果如下：\" + \"-\" * 40)\n",
    "    print(result)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5644972a-11c7-409c-b0c3-e7f5f6f40119",
   "metadata": {},
   "source": [
    "任务七："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "584964a5-2d7f-4f40-87b5-748d13e79f73",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------------用户管理系统------------\n",
      "1.添加  2.删除  3.显示  0.退出\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请选择： 1\n",
      "请输入用户名： 吴林炜\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "用户已存在！\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入用户名： 2\n",
      "请输入密码： 123456\n",
      "添加成功，继续？(Y/N) n\n",
      "请选择： 3\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         用户信息         \n",
      "----------------------\n",
      "| 用户名        | 密码       |\n",
      "----------------------\n",
      "| 霍元甲   hyj |        |\n",
      "| 陈真     cz |        |\n",
      "| 郭靖        | gj     |\n",
      "| 黄蓉        | hr     |\n",
      "| 张无忌       | zwj    |\n",
      "| 李莫愁       | lmc    |\n",
      "| wsq       | wsq    |\n",
      "| 吴林炜       | 123456 |\n",
      "| n         | 123456 |\n",
      "| 2         | 123456 |\n",
      "----------------------\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请选择： 2\n",
      "请输入要删除的用户名： 霍元甲\n",
      "用户不存在，重新输入？(Y/N) 陈真\n",
      "请选择： 郭靖\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入错误！\n"
     ]
    }
   ],
   "source": [
    "#coding=utf8\n",
    "users = {}\n",
    "\n",
    "def readFile(file):\n",
    "    \"\"\"读取用户信息，兼容多种编码\"\"\"\n",
    "    try:\n",
    "        # 尝试多种编码读取，解决解码错误\n",
    "        for encoding in ['utf-8', 'gbk', 'latin-1']:\n",
    "            try:\n",
    "                with open(file, \"r+\", encoding=encoding) as fp:\n",
    "                    for line in fp:\n",
    "                        line = line.strip()\n",
    "                        if ',' in line:\n",
    "                            u, p = line.split(',', 1)\n",
    "                            users[u.strip()] = p.strip()\n",
    "                return users\n",
    "            except UnicodeDecodeError:\n",
    "                continue\n",
    "        # 所有编码尝试失败则创建新文件\n",
    "        open(file, \"w\").close()\n",
    "    except FileNotFoundError:\n",
    "        open(file, \"w\").close()\n",
    "    return users\n",
    "\n",
    "def saveFile(file):\n",
    "    \"\"\"保存用户信息\"\"\"\n",
    "    with open(file, \"w\", encoding=\"utf-8\") as fp:\n",
    "        fp.writelines(f\"{k},{v}\\n\" for k, v in users.items())\n",
    "\n",
    "def add_user():\n",
    "    \"\"\"添加用户\"\"\"\n",
    "    while True:\n",
    "        u = input(\"请输入用户名：\").strip()\n",
    "        if not u:\n",
    "            print(\"用户名不能为空！\")\n",
    "            continue\n",
    "        if u in users:\n",
    "            print(\"用户已存在！\")\n",
    "            continue\n",
    "        p = input(\"请输入密码：\").strip()\n",
    "        if not p:\n",
    "            print(\"密码不能为空！\")\n",
    "            continue\n",
    "        users[u] = p\n",
    "        saveFile(\"users.csv\")\n",
    "        if input(\"添加成功，继续？(Y/N)\").lower() != 'y':\n",
    "            break\n",
    "\n",
    "def delete_user():\n",
    "    \"\"\"删除用户\"\"\"\n",
    "    while True:\n",
    "        u = input(\"请输入要删除的用户名：\").strip()\n",
    "        if not u:\n",
    "            print(\"用户名不能为空！\")\n",
    "            continue\n",
    "        if u in users:\n",
    "            if input(\"确定删除？(Y/N)\").lower() == 'y':\n",
    "                del users[u]\n",
    "                saveFile(\"users.csv\")\n",
    "                print(\"已删除！\")\n",
    "                if input(\"继续删除？(Y/N)\").lower() != 'y':\n",
    "                    break\n",
    "            else:\n",
    "                break\n",
    "        else:\n",
    "            if input(\"用户不存在，重新输入？(Y/N)\").lower() != 'y':\n",
    "                break\n",
    "\n",
    "def display_user():\n",
    "    \"\"\"显示用户\"\"\"\n",
    "    if not users:\n",
    "        print(\"无用户信息\")\n",
    "        return\n",
    "    max_u = max(len(u) for u in users)\n",
    "    max_p = max(len(p) for p in users.values())\n",
    "    w = max_u + max_p + 7\n",
    "    print(\"用户信息\".center(w))\n",
    "    print('-' * w)\n",
    "    print(f\"| 用户名{' '*(max_u-2)} | 密码{' '*(max_p)} |\")\n",
    "    print('-' * w)\n",
    "    for u, p in users.items():\n",
    "        print(f\"| {u.ljust(max_u)} | {p.ljust(max_p)} |\")\n",
    "    print('-' * w)\n",
    "\n",
    "def menu():\n",
    "    \"\"\"主菜单\"\"\"\n",
    "    print(\"用户管理系统\".center(30, '-'))\n",
    "    print(\"1.添加  2.删除  3.显示  0.退出\")\n",
    "    while True:\n",
    "        c = input(\"请选择：\")\n",
    "        if c == '1':\n",
    "            add_user()\n",
    "        elif c == '2':\n",
    "            delete_user()\n",
    "        elif c == '3':\n",
    "            display_user()\n",
    "        elif c == '0':\n",
    "            break\n",
    "        else:\n",
    "            print(\"输入错误！\")\n",
    "\n",
    "def main():\n",
    "    readFile(\"users.csv\")\n",
    "    menu()\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6fde5f3-13ac-4d84-b0df-532b2122766a",
   "metadata": {},
   "outputs": [],
   "source": [
    "任务八："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9f5bb972-c304-4673-a9bd-be2e22cd5f08",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------------------------------------------------------------\n",
      "                            跳转登录                            \n",
      "------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "输入用户名:  吴林炜\n",
      "请输入密码:  admin\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "登录成功!\n",
      "判断用户是否具有权限..\n",
      "正在删除信息...\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "class UserPermissionManager:\n",
    "    def __init__(self):\n",
    "        # 初始化用户数据\n",
    "        self.data = {\n",
    "            \"吴林炜\": {\"password\": \"admin\", \"is_super\": 1},  # 有权限用户\n",
    "            \"test\": {\"password\": \"123\", \"is_super\": 0}   # 测试用户无权限用户\n",
    "        }\n",
    "        self.login_user_session = {}  # 当前登录用户信息\n",
    "\n",
    "    # 定义判断用户是否登录的装饰器（使用 staticmethod 避免 self 干扰）\n",
    "    @staticmethod\n",
    "    def is_login(fun):\n",
    "        def wrapper(*args, **kwargs):\n",
    "            # 这里假设实例是第一个参数（self）\n",
    "            self = args[0]\n",
    "            # 检查是否已登录\n",
    "            if self.login_user_session:\n",
    "                # 已登录，直接执行目标函数\n",
    "                result = fun(*args, **kwargs)\n",
    "                return result\n",
    "            else:\n",
    "                # 未登录，跳转登录流程\n",
    "                print(\"-\" * 60)\n",
    "                print(\"跳转登录\".center(60, \" \"))\n",
    "                print(\"-\" * 60)\n",
    "                user = input(\"输入用户名: \")\n",
    "                passwd = input(\"请输入密码: \")\n",
    "\n",
    "                # 验证用户名是否存在\n",
    "                if user in self.data:\n",
    "                    # 用户名存在，验证密码\n",
    "                    if self.data[user][\"password\"] == passwd:\n",
    "                        # 密码正确，记录登录状态\n",
    "                        self.login_user_session[\"username\"] = user\n",
    "                        print(\"登录成功!\")\n",
    "                        # 执行目标函数\n",
    "                        result = fun(*args, **kwargs)\n",
    "                        return result\n",
    "                    else:\n",
    "                        # 密码错误\n",
    "                        print(\"密码错误!\")\n",
    "                        return None\n",
    "                else:\n",
    "                    # 用户名不存在\n",
    "                    print(\"该用户不存在!\")\n",
    "                    return None\n",
    "        return wrapper\n",
    "\n",
    "    # 定义判断用户是否具有权限的装饰器（使用 staticmethod 避免 self 干扰）\n",
    "    @staticmethod\n",
    "    def is_permission(fun):\n",
    "        def wrapper2(*args, **kwargs):\n",
    "            # 这里假设实例是第一个参数（self）\n",
    "            self = args[0]\n",
    "            print(\"判断用户是否具有权限..\")\n",
    "            # 获取当前登录用户名\n",
    "            current_user = self.login_user_session.get(\"username\")\n",
    "            # 验证当前用户的权限\n",
    "            if self.data[current_user][\"is_super\"] == 1:\n",
    "                # 有权限，执行目标函数\n",
    "                result = fun(*args, **kwargs)\n",
    "                return result\n",
    "            else:\n",
    "                # 无权限，提示并返回None\n",
    "                print(f\"用户{current_user}没有权限!\")\n",
    "                return None\n",
    "        return wrapper2\n",
    "\n",
    "    # 删除功能（应用装饰器）\n",
    "    @is_login          # 先判断登录\n",
    "    @is_permission     # 再判断权限\n",
    "    def delete(self):\n",
    "        # 目标功能：删除信息（模拟）\n",
    "        return \"正在删除信息...\"\n",
    "\n",
    "    # 主方法：触发整个流程\n",
    "    def run(self):\n",
    "        result = self.delete()\n",
    "        print(result)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    manager = UserPermissionManager()\n",
    "    manager.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd0c6efc-2fc6-406b-8519-5a3bf718b60b",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
